package cn.yhp.mybatis.session.defaults;

import cn.yhp.mybatis.executor.Executor;
import cn.yhp.mybatis.mapping.BoundSql;
import cn.yhp.mybatis.mapping.Environment;
import cn.yhp.mybatis.mapping.MappedStatement;
import cn.yhp.mybatis.session.Configuration;
import cn.yhp.mybatis.session.SqlSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author yhp
 * @description 默认SqlSession实现类
 * @date 2023/11/8
 */
public class DefaultSqlSession implements SqlSession {

    private Logger logger= LoggerFactory.getLogger(DefaultSqlSession.class);

    /**
     * 映射器注册机
     */
//    private MapperRegistry mapperRegistry;

    private Configuration configuration;

    /**
     * 执行器
     */
    private Executor executor;

    public DefaultSqlSession(Configuration configuration, Executor executor) {
        this.configuration = configuration;
        this.executor = executor;
    }
    @Override
    public <T> T selectOne(String statement) {
        return (T)("你被代理了："+statement);
    }

    @Override
    public <T> T selectOne(String statement, Object parameter) {
        try {
            // 获取封装映射sql语句
            MappedStatement mappedStatement = configuration.getMappedStatement(statement);

            List<T> list = executor.query(mappedStatement, parameter, Executor.NO_RESULT_HANDLER, mappedStatement.getBoundSql());
            return list.get(0);
//            // 获取环境对象【含数据源和事务管理】
//            Environment environment = configuration.getEnvironment();
//            Connection connection = environment.getDataSource().getConnection();
//            BoundSql boundSql = mappedStatement.getBoundSql();
//            logger.info("selectOne SQL:{},参数：{}",boundSql.getSql(),parameter);
//            // 获取预编译语句对象
//            PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSql());
//            // 暂定写死一个固定类型参数
//            preparedStatement.setLong(1,Long.parseLong(((Object[])parameter)[0].toString()));
//            ResultSet resultSet = preparedStatement.executeQuery();
//            // 查询数据类型转换
//            List<T> objList = resultSet2Obj(resultSet, Class.forName(boundSql.getResultType()));
//            return objList.get(0);
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
//        return (T) ("你被代理了！" + "\n方法：" + statement + "\n入参：" + parameter + "\n待执行SQL：" + mappedStatement.getSql());
    }


    @Override
    public <T> T getMapper(Class<T> type) {
        return configuration.getMapper(type,this);
    }

    @Override
    public Configuration getConfiguration() {
        return configuration;
    }
}
